/*
 * Copyright (c) csii.com.cn 2016 zhaojin
 */
define(['zepto-custom', 'underscore'], function ($, _) {
    'use strict';

    if (typeof $ === 'undefined') {
        throw new Error('app\'s script requires $');
    }


    var objs = {
        //微信组件相关
        $toastOK: $('#toastOK'),
        $toastOKP: $('#toastOK p.weui_toast_content'),
        $toastError: $('#toastError'),
        $toastErrorP: $('#toastError p.weui_toast_content'),
        $loadingToast: $('#loadingToast'),
        $alertOk: $('#alertOk'),
        $alertOkMsgDiv: $('#alertOk div.weui_dialog_bd'),
        $alertOkBtn: $('#alertOk #alertOkBtn'),
        $confirm: $('#confirm'),
        $confirmMsgDiv: $('#confirm div.weui_dialog_bd'),
    };

    var dict = {
        RES: 'res',
        status: 'status',
        successFlag: '0000',
        failFlag: '4444',
        msg: 'msg',
        errmsg: 'errmsg',
        errcode: 'errcode',
        DEV: 'DEV',
        TEST: 'TEST',
        PRO: 'PRO',
        IE: 'IE'
    };

    var options = {
        ctxPath:null,
        requesting: false,
        mode: 'DEV',
        clientExploer: 'IE',
        URL404: '404',
        URL500: '500',
    };

    var privateMethods = {
        initApp: function (o) {
            o.ctxPath = document.getElementById('contextPath').value,
                o.mode = document.getElementById('appMode').value,
                o.clientExploer = document.getElementById('clientExploer').value
        },
        ajax: function (params) {
            options.requesting = true;
            var _showmask = !!params['showmask'];
            if (_showmask) {
                app.loading();
            }
            if (options.clientExploer !== dict.IE) {
                console.log(' params>>>', params);
            }
            $.ajax({
                url: params.url,
                type: params.type,
                dataType: params.dataType,
                timeout: !params.timeout ? params.timeout : 6000,
                data: params.data,
                success: function (res) {
                    if (options.clientExploer !== dict.IE) {
                        console.log('res>>>', res);
                    }

                    if (res) {
                        var data = res[dict.RES];

                        if (data) {
                            if (options.clientExploer !== dict.IE) {
                                console.log('data>>>', data);
                            }
                            var status = data[dict.status];
                            if (!status) {
                                //约定不允许返回无系统状态的结果
                                throw new Error('\'s 约定不允许返回无系统状态的结果')
                            }
                            var msg, errcode;
                            var needDelay = true;
                            //状态码为平台自身约定
                            switch (status) {
                                case dict.successFlag:
                                    msg = data[dict.msg];
                                    if (msg) {
                                        app.toastOk(msg);
                                    }
                                    else {
                                        needDelay = false;
                                    }

                                    //给用户一些时间看提示信息
                                    if (_.isFunction(params.success)) {
                                        if (needDelay) {
                                            setTimeout(function () {
                                                params.success(data);
                                            }, 1500);
                                        } else {
                                            params.success(data);
                                        }
                                    } else {
                                        if (options.clientExploer !== dict.IE) {
                                            console.log('warn:你确认这次请求不需要进行成功处理?');
                                        }
                                    }

                                    break;
                                case dict.failFlag:
                                    msg = data[dict.errmsg];
                                    errcode = data[dict.errcode];
                                    if (_.isFunction(params.error)) {
                                        params.error(data, msg, errcode);
                                    } else {
                                        if (options.clientExploer !== dict.IE) {
                                            console.error('error:出错了:', (msg ? msg : '无错误详情 :（）'), errcode);
                                        }
                                        if (msg) {
                                            app.toastError('[errcode] ' + msg);
                                        }
                                    }
                                    break;
                            }

                        } else {
                            //约定不允许返回无系统状态的结果
                            if (options.clientExploer !== dict.IE) {
                                console.error('error:后台没有响应内容!!!');
                            }
                        }
                    }

                }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                    switch (XMLHttpRequest.status) {
                        case 404:
                            if (_.isFunction(params['error404'])) {
                                params.error404(XMLHttpRequest, textStatus, errorThrown);
                            } else {
                                if (options.mode === dict.DEV) {
                                    console.error('\'s 404!!!');
                                } else {
                                    alert(404);
                                    // window.location.href = options.URL404;
                                }
                            }
                            break;
                        case 500:
                            if (options.mode === dict.DEV) {
                                console.error('\'s 500!!!')
                            } else {
                                alert(500);
                                // window.location.href = options.URL500;
                            }
                            break;
                        default:
                            if (options.mode === dict.DEV) {
                                console.error('\'s ' + textStatus + '!!!' + ' (' + errorThrown + ')')
                            } else {
                                alert(XMLHttpRequest.status);
                                // window.location.href = options.URL500;
                            }
                            break;
                    }
                }, complete: function () {
                    options.requesting = false;
                    if (options.clientExploer !== dict.IE) {
                        console.log('complete>>>', typeof params.complete)
                    }
                    if (_.isFunction(params.complete)) {
                        params.complete();
                    }
                    if (_showmask) {
                        app.unLoading();
                    }
                }
            })
        }
    };

    var app = {
        options: options,
        init: function (params) {
            privateMethods.initApp(this.options);
            this.options = $.extend(options, params);
        },
        loading: function () {
            objs.$loadingToast.show();
        },
        unLoading: function () {
            objs.$loadingToast.hide();
        },
        get: function (params) {
            params['type'] = 'GET';
            params['dataType'] = 'json';
            params['timeout'] = '6000';
            privateMethods.ajax(params);
        },
        post: function (params) {
            params['type'] = 'POST';
            params['dataType'] = 'json';
            params['timeout'] = '6000';
            privateMethods.ajax(params);
        },
        toastOk: function (params) {
            var msg = params['msg'];//str
            var nouseIcons = params['nouseIcons'];//bool
            var needMask = params['needMask'];//bool
            var useRuYi = params['useRuYi'];//bool
            var $weui_icon_toast = objs.$toastOK.find('.weui_icon_toast');
            var $toastOK_ruyi = objs.$toastOK.find('#toastOK-ruyi');

            if (useRuYi) {
                $weui_icon_toast.hide();
                $toastOK_ruyi.css({display: 'block'}).addClass('animated flip');
            }
            if (useHTStxt) {
                $weui_icon_toast.hide();
                $toastOK_htstxt.css({display: 'block'}).addClass('animated flip');
            }
            if (!!nouseIcons) {
                $weui_icon_toast.hide();
            }
            if (!!needMask) {
                objs.$toastOK.find('.weui_mask_transparent').show();
            }
            objs.$toastOKP.html(msg);
            objs.$toastOK.show();
            setTimeout(function () {
                objs.$toastOK.hide();
            }, 1500);
        },
        toastError: function (msg) {
            objs.$toastErrorP.html(msg);
            objs.$toastError.show();
            setTimeout(function () {
                objs.$toastError.hide();
            }, 3000);
        },
        alertOk: function (params) {
            var msg, priCallBckFunc, noTitile;
            msg = params['msg'];
            priCallBckFunc = params['priCallBckFunc'];
            noTitile = params['noTitile'];

            objs.$alertOkMsgDiv.html(msg);
            objs.$alertOkBtn.on('tap', function () {
                if (_.isFunction(priCallBckFunc)) {
                    priCallBckFunc();
                    objs.$alertOk.hide();
                }
            });
            if (!!noTitile) {
                $('#alertOk .weui_dialog_hd').remove();
            }
            objs.$alertOk.show();
        },
        confirm: function (params) {
            var msg, onCancelCallbackFunc, onConfirmCallbackFunc, noTitile;
            msg = params['msg'];
            onCancelCallbackFunc = params['onCancelCallbackFunc'];
            onConfirmCallbackFunc = params['onConfirmCallbackFunc'];

            objs.$confirmMsgDiv.html(msg);

            objs.$confirm.find('#cancleBtn').on('tap', function () {
                if (_.isFunction(onCancelCallbackFunc)) {
                    onCancelCallbackFunc();
                    objs.$confirm.hide();
                }
            });

            objs.$confirm.find('#confrimBtn').on('tap', function () {
                if (_.isFunction(onConfirmCallbackFunc)) {
                    onConfirmCallbackFunc();
                    objs.$confirm.hide();
                }
            });

            noTitile = params['noTitile'];
            if (!!noTitile) {
                $('#confirm .weui_dialog_hd').remove();
            }
            objs.$confirm.show();
        }
    };

    return app;
});